package com.linkage.jz.bankruptcy.activity.Project.ZQUser.DetailOper;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.ApplyChangerZQUserNameBean;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.ApplyBaseReplyDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.base.BaseWhiteCreateActivity;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ApplyEditProxyUserActivity extends BaseCreateActivity {

    private int REQUEST_CODE_ADDRESS = 10001;
    private String projectId;
    private String creditorId;

    // 代理人授权委托
    private RecyclerView recyclerImgsNumber;
    private List<UploadImage> imageListNumber = new ArrayList<>();
    private GridImagesAdapter imgAdapterNumber;

    private RecyclerView recyclerImgsWt;
    private List<UploadImage> imageListWt = new ArrayList<>();
    private GridImagesAdapter imgAdapterWt;

    // 代理人授权委托
    private RecyclerView recyclerImgsNumber_o;
    private List<UploadImage> imageListNumber_o = new ArrayList<>();
    private GridImagesAdapter imgAdapterNumber_o;

    private RecyclerView recyclerImgsWt_o;
    private List<UploadImage> imageListWt_o = new ArrayList<>();
    private GridImagesAdapter imgAdapterWt_o;




    private TextView btn_commit,back_black;

    private static final int TYPE_UPLOAD = 0; // 0:线上,1:线下
    private static final int TYPE_LOCAL = 1;

    private TextView proxyUserName;
    private TextView proxyUserPhone;
    private TextView proxyUserEmail;
    private TextView proxyUserOtherPhone;
    private TextView proxyRegisterNumber;
    private TextView sendAddress;

    private TextView proxyUserName_old;
    private TextView proxyUserPhone_old;
    private TextView proxyUserEmail_old;
    private TextView proxyUserOtherPhone_old;
    private TextView proxyRegisterNumber_old;
    private TextView sendAddress_old;


    private static int mType; //0新增 1修改
    private ApplyBaseReplyDialog dialog;

    PublicNoticeDialog noticeDialog;
    private static ApplyChangerZQUserNameBean mInfo;

    public static void start(Context context, ApplyChangerZQUserNameBean bean, int type) {
        Intent intent = new Intent(context, ApplyEditProxyUserActivity.class);
        mInfo = bean;
        mType = type;
        context.startActivity(intent);

    }

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        setContentView(R.layout.activity_apply_edit_proxy_user);
        super.onCreate(savedInstanceState);

        back_black = findViewById(R.id.top_back1);
        back_black.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titlebar_title = findViewById(R.id.top_title);
        if(mType ==0) {
            titlebar_title.setText("更改代理人审核");
        }else{
            titlebar_title.setText("更改代理人");
        }

//        if (mType == 0) {
//            setContentView(R.layout.activity_apply_edit_proxy_user, "更改代理人审核");
//        } else {
//            setContentView(R.layout.activity_apply_edit_proxy_user, "更改代理人");
//        }

        initViewdata();
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_ADDRESS) {
//                address = (AddressInfo) data.getSerializableExtra("address");
//                tvAddr.setText(address.getDetailString());
                sendAddress.setTag(data.getStringExtra("id"));
                sendAddress.setText(data.getStringExtra("desc"));
            }
        }
    }

//    @Override
//    public void finish() {
////
//        finish();
//    }
public  void initView() {
}

    public  void initViewdata() {
        projectId = getIntent().getStringExtra("projectId");
        creditorId = getIntent().getStringExtra("creditorId");

        proxyUserName = (TextView) findViewById(R.id.proxy_user_name);
        proxyUserPhone = (TextView) findViewById(R.id.proxy_user_phone);
        proxyRegisterNumber = (TextView) findViewById(R.id.proxy_register_number);
        proxyUserOtherPhone = (TextView) findViewById(R.id.proxy_user_other_phone);
        proxyUserEmail = (TextView) findViewById(R.id.proxy_user_email);

        findViewById(R.id.top_mune1).setVisibility(View.INVISIBLE);
        sendAddress = (TextView) findViewById(R.id.send_address);


        proxyUserName_old = (TextView) findViewById(R.id.proxy_user_name_old);
        proxyUserPhone_old = (TextView) findViewById(R.id.proxy_user_phone_old);
        proxyRegisterNumber_old = (TextView) findViewById(R.id.proxy_register_number_old);
        proxyUserOtherPhone_old = (TextView) findViewById(R.id.proxy_user_other_phone_old);
        proxyUserEmail_old = (TextView) findViewById(R.id.proxy_user_email_old);

        sendAddress_old = (TextView) findViewById(R.id.send_address_old);


        // 代理人授权委托
//        private RecyclerView recyclerImgsNumber;
//        private List<UploadImage> imageListNumber = new ArrayList<>();
//        private GridImagesAdapter imgAdapterNumber;

        recyclerImgsNumber = findViewById(R.id.recycler_imgs_number);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerImgsNumber.setLayoutManager(manager);
        imgAdapterNumber = new BaseCreateActivity.GridImagesAdapter(ApplyEditProxyUserActivity.this, TYPE_PREVIEW);
        imgAdapterNumber.setList(imageListNumber);
        recyclerImgsNumber.setAdapter(imgAdapterNumber);
        imgAdapterNumber.setEnable(false);


        recyclerImgsWt = findViewById(R.id.recycler_imgs_wt);
        FullyGridLayoutManager manager1 = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerImgsWt.setLayoutManager(manager1);
        imgAdapterWt = new BaseCreateActivity.GridImagesAdapter(ApplyEditProxyUserActivity.this, TYPE_PREVIEW);
        imgAdapterWt.setList(imageListWt);
        recyclerImgsWt.setAdapter(imgAdapterWt);
        imgAdapterWt.setEnable(false);

        recyclerImgsNumber_o = findViewById(R.id.recycler_imgs_number_old);

        FullyGridLayoutManager manager2 = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerImgsNumber_o.setLayoutManager(manager2);
        imgAdapterNumber_o = new BaseCreateActivity.GridImagesAdapter(ApplyEditProxyUserActivity.this, TYPE_PREVIEW);
        imgAdapterNumber_o.setList(imageListNumber_o);
        recyclerImgsNumber_o.setAdapter(imgAdapterNumber_o);
        imgAdapterNumber_o.setEnable(false);


        recyclerImgsWt_o = findViewById(R.id.recycler_imgs_wt_old);
        FullyGridLayoutManager manager3 = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerImgsWt_o.setLayoutManager(manager3);
        imgAdapterWt_o = new BaseCreateActivity.GridImagesAdapter(ApplyEditProxyUserActivity.this, TYPE_PREVIEW);
        imgAdapterWt_o.setList(imageListWt_o);
        recyclerImgsWt_o.setAdapter(imgAdapterWt_o);
        imgAdapterWt_o.setEnable(false);

        btn_commit = findViewById(R.id.btn_commit);
        if (mType == 0) {
            btn_commit.setVisibility(View.VISIBLE);
        } else {
            btn_commit.setVisibility(View.GONE);
        }

        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog = new ApplyBaseReplyDialog(ApplyEditProxyUserActivity.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_save) {
                            String msg = dialog.text_reason.getText().toString().trim();
                            String status = "1";
                            if (dialog.cb_nopass.isChecked()) {
                                status = "2";
                            }
                            String notifyTypes = "";
                            if (dialog.send_msg.isChecked() && dialog.send_phone.isChecked()) {
                                notifyTypes = "0,1";
                            } else if (dialog.send_msg.isChecked()) {
                                notifyTypes = "0";
                            } else {
                                notifyTypes = "1";
                            }


//                    addZQUser(name,phone);
                            applyPerson(status, msg, notifyTypes);
                            dialog.dismiss();
                        }
                        if (v.getId() == R.id.btn_chancel) {
                            dialog.dismiss();
                        }

                    }
                });
                dialog.show();
            }
        });

//        recyclerImgsNumber.setLayoutManager(new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL,
//                false));
//        imgAdapterNumber = new GridImagesAdapter(this, TYPE_EDIT);
//        imgAdapterNumber.setList(imageListNumber);
//        recyclerImgsNumber.setAdapter(imgAdapterNumber);
//
//        recyclerImgsWt.setLayoutManager(new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL,
//                false));
//        imgAdapterWt = new GridImagesAdapter(this, TYPE_EDIT);
//        imgAdapterWt.setList(imageListWt);
//        recyclerImgsWt.setAdapter(imgAdapterWt);

        if (mInfo != null) {
//            et_Name.setText(mInfo.getCreditorName());
//            et_socialcode.setText(mInfo.getSocialUniformCreditCode());
//            et_fddbz.setText(mInfo.getLegalRepresentativeName());


            if (mInfo.getChange() != null) {
                proxyUserName.setText(mInfo.getChange().getAgentName());
                proxyUserPhone.setText(mInfo.getChange().getContact());
                proxyUserEmail.setText(mInfo.getChange().getEmail());
                proxyUserOtherPhone.setText(mInfo.getChange().getOtherContact());
                proxyRegisterNumber.setText(mInfo.getChange().getCreditorsIDCardNumber());

                String addr = "";
                if (mInfo.getChange().getAddressInfo() != null) {
                    if (mInfo.getChange().getAddressInfo().getProvince() != null) {
                        addr = mInfo.getChange().getAddressInfo().getProvince();
                    }

                    if (mInfo.getChange().getAddressInfo().getCity() != null) {
                        addr += mInfo.getChange().getAddressInfo().getCity();
                    }

                    if (mInfo.getChange().getAddressInfo().getRegion() != null) {
                        addr += mInfo.getChange().getAddressInfo().getRegion();
                    }

                    if (mInfo.getChange().getAddressInfo().getAddress() != null) {
                        addr += mInfo.getChange().getAddressInfo().getAddress();
                    }

                }
                sendAddress.setText(addr);

                if(mInfo.getChange().getProvidePowerAttorneyChangeAttas()!=null) {
                    for (int i = 0; i < mInfo.getChange().getProvidePowerAttorneyChangeAttas().size(); i++) {
                        TaskAtta atta = mInfo.getChange().getProvidePowerAttorneyChangeAttas().get(i);
                        JSONObject obj = new JSONObject();
                        try {
                            obj.putOpt("filename", atta.getAttachmentName());
                            obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                            obj.putOpt("filesize", atta.getAttachmentSize());
                            obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
                            imageListNumber.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if(mInfo.getChange().getCreditorsProvideCardChangeAttas()!=null) {
                    for (int i = 0; i < mInfo.getChange().getCreditorsProvideCardChangeAttas().size(); i++) {
                        TaskAtta atta = mInfo.getChange().getCreditorsProvideCardChangeAttas().get(i);
                        JSONObject obj = new JSONObject();
                        try {
                            obj.putOpt("filename", atta.getAttachmentName());
                            obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                            obj.putOpt("filesize", atta.getAttachmentSize());
                            obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
                            imageListWt.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

            if (mInfo.getCreditorInfo() != null) {
                proxyUserName_old.setText(mInfo.getCreditorInfo().getAgentName());
                proxyUserPhone_old.setText(mInfo.getCreditorInfo().getContact());
                proxyUserEmail_old.setText(mInfo.getCreditorInfo().getEmail());
                proxyUserOtherPhone_old.setText(mInfo.getCreditorInfo().getOtherContact());
                proxyRegisterNumber_old.setText(mInfo.getCreditorInfo().getCreditorsIDCardNumber());

                String addr = "";
                if (mInfo.getCreditorInfo().getAddressInfo() != null) {
                    if (mInfo.getCreditorInfo().getAddressInfo().getProvince() != null) {
                        addr = mInfo.getCreditorInfo().getAddressInfo().getProvince();
                    }

                    if (mInfo.getCreditorInfo().getAddressInfo().getCity() != null) {
                        addr += mInfo.getCreditorInfo().getAddressInfo().getCity();
                    }

                    if (mInfo.getCreditorInfo().getAddressInfo().getRegion() != null) {
                        addr += mInfo.getCreditorInfo().getAddressInfo().getRegion();
                    }

                    if (mInfo.getCreditorInfo().getAddressInfo().getAddress() != null) {
                        addr += mInfo.getCreditorInfo().getAddressInfo().getAddress();
                    }

                }
                sendAddress_old.setText(addr);
                if(mInfo.getCreditorInfo().getProvidePowerAttorneyAttas()!=null) {
                    for (int i = 0; i < mInfo.getCreditorInfo().getProvidePowerAttorneyAttas().size(); i++) {
                        TaskAtta atta = mInfo.getCreditorInfo().getProvidePowerAttorneyAttas().get(i);
                        JSONObject obj = new JSONObject();
                        try {
                            obj.putOpt("filename", atta.getAttachmentName());
                            obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                            obj.putOpt("filesize", atta.getAttachmentSize());
                            obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
                            imageListNumber_o.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if(mInfo.getCreditorInfo().getCreditorsProvideCardAttas()!=null) {
                    for (int i = 0; i < mInfo.getCreditorInfo().getCreditorsProvideCardAttas().size(); i++) {
                        TaskAtta atta = mInfo.getCreditorInfo().getCreditorsProvideCardAttas().get(i);
                        JSONObject obj = new JSONObject();
                        try {
                            obj.putOpt("filename", atta.getAttachmentName());
                            obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                            obj.putOpt("filesize", atta.getAttachmentSize());
                            obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
                            imageListWt_o.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
//                if(mInfo.getCreditorInfo().getCreditorsProvideCardChangeAttas()!=null) {
//                    for (int i = 0; i < mInfo.getCreditorInfo().getCreditorsProvideCardChangeAttas().size(); i++) {
//                        TaskAtta atta = mInfo.getCreditorInfo().getCreditorsProvideCardChangeAttas().get(i);
//                        JSONObject obj = new JSONObject();
//                        try {
//                            obj.putOpt("filename", atta.getAttachmentName());
//                            obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
//                            obj.putOpt("filesize", atta.getAttachmentSize());
//                            obj.putOpt("loadUrl", atta.getAttachmentPreviewAddress());
//                            imageListNumber.add(new Gson().fromJson(obj.toString(), UploadImage.class));
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
            }
        }
    }


    public void applyPerson(String status, String msg, String notifyTypes) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            return;
        }

        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId", "");

//        String no = zqUserDetailInfo.get(0).getId();
        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
//                .add("creditorId", creditorId)
                .add("auditState", status)
                .add("auditDesc", msg)
                .add("noticeTypes", notifyTypes)
                .add("projectId", mInfo.getChange().getBankruptcyProjectId())
                .add("changeId", mInfo.getChange().getId())
                .add("auditType", "5")
                .build();

        String url = Consts.WEBURL_RIGHTSAUDIT;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(ApplyEditProxyUserActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
//

                String str = response.body().string();
                try {
                    final JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                ToastUtil.getInstance(ApplyEditProxyUserActivity.this).showShortToast("审核成功");
                                finish();
//                                Toast.makeText(ApplyChangerZQUserNameActivity.this, "替吉奥成功", Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();

                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ApplyEditProxyUserActivity.this, "保存失败" + object.optString("msg"), Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                } catch (Exception ex) {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(ApplyEditProxyUserActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

}
